package com.hzw.saas.common.config.util;


import java.util.ArrayList;
import java.util.List;

import com.hzw.saas.common.config.bo.BaseTree;

/**
 * @author syh
 */
public class TreeUtils {

    /**
     * 格式化list为树形list
     *
     * @param list
     * @param flag true 表示全部展开，false 表示不展开
     * @return
     */
    public static <T extends BaseTree> List<T> formatTree(List<T> list, Boolean flag) {

        List<T> nodeList = new ArrayList<T>();
        for (T node1 : list) {
            boolean mark = false;
            for (T node2 : list) {
                if (node1.getParentId() != null && node1.getParentId().equals(node2.getPid())) {
                    node2.setLeaf(false);
                    mark = true;
                    if (node2.getChildren() == null) {
                        node2.setChildren(new ArrayList<BaseTree>());
                    }
                    node2.getChildren().add(node1);
                    if (flag) {
                        //默认已经全部展开
                    } else {
                        node2.setExpanded(false);
                    }
                    break;
                }
            }
            if (!mark) {
                nodeList.add(node1);
                if (flag) {
                    //默认已经全部展开
                } else {
                    node1.setExpanded(false);
                }
            }
        }
        return nodeList;
    }


    public static <T extends BaseTree> List<T> buildTree(List<T> treeNodes) {
        List<T> trees = new ArrayList();
        for (T treeNode : treeNodes) {
            if ("0".equals(treeNode.getParentId().toString())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    public static <T extends BaseTree> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getPid().equals(it.getParentId())) {
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

}

